package com.ygqh.baby.controller.admin;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ygqh.baby.ao.DataStatus;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.controller.utils.DocumentHandler;
import com.ygqh.baby.po.AdminContractArrive;
import com.ygqh.baby.po.AdminMaterial;
import com.ygqh.baby.po.AdminMaterialDetail;
import com.ygqh.baby.po.AdminSupplierInvoice;
import com.ygqh.baby.service.AdminMaterialDetailService;
import com.ygqh.baby.service.AdminMaterialService;
import com.ygqh.baby.service.AdminMaterialService;
import com.ygqh.baby.service.FileService;

@Controller
@RequestMapping("/admin/material")
public class MaterialController  extends BaseController<Object, java.lang.Long>{
	
    @Autowired
	private AdminMaterialService adminMaterialService;	
    @Autowired
  	private AdminMaterialDetailService adminMaterialDetailService;	
    @Autowired
  	private FileService fileService;
	
	@RequestMapping("searchMaterial")
	@ResponseBody
	public Map<String,Object> searchMaterial(String q,QueryInfo queryInfo) {
		
		ResultSet<AdminMaterial> resultSet=adminMaterialService.search(queryInfo,q);
		
		return resultSet.toDatatables(null);
	}
	@RequestMapping("searchMaterialList")
	@ResponseBody
	public List<AdminMaterial> searchMaterialList() {
		return adminMaterialService.find();
		
		
	}
	@RequestMapping("saveMaterial")
	@ResponseBody
	public Message saveMaterial(String name,Long id) {
		AdminMaterial Material=new AdminMaterial();
		Material.setName(name);
		Material.setId(id);
		
		Material.setCreateBy(getSession().getTrueName());
		Material.setCreateTime(new Date());
		//判断是否含有相同的名字
		if(checkName(name,id)>0)
			return Message.error("分类名称已经存在");
	   return adminMaterialService.saveOrUpdate(Material)==1?SUCCESS_MESSAGE:ERROR_MESSAGE;
	
	}
	@RequestMapping("updateMaterialStatus")
	@ResponseBody
	public Message updateMaterialStatus(Long id) {
		AdminMaterial adminMaterial=new AdminMaterial();		
		adminMaterial.setId(id);
		adminMaterial.setUpdateBy(getSession().getTrueName());	
		adminMaterial.setUpdateTime(new Date());	
		adminMaterial.setStatus(DataStatus.Delete);
	   return adminMaterialService.update(adminMaterial)==1?SUCCESS_MESSAGE:ERROR_MESSAGE;
	
	}
	private int checkName(String name,Long id){
		return adminMaterialService.findName(name, id);
	}
	
	@RequestMapping("searchMaterialDetail")
	@ResponseBody
	public Map<String,Object> searchMaterialDetail(Long batchId,QueryInfo queryInfo,String contractCode) {
		
		ResultSet<AdminMaterialDetail> resultSet=adminMaterialDetailService.search(queryInfo, batchId, contractCode);
		
		return resultSet.toDatatables(null);
	}
	
	//导入供应商发票
		@RequestMapping("readTemplate")
		@ResponseBody
		public List<Map<String,Object>> readTemplate(@RequestParam("uploadFile") MultipartFile uploadFile,HttpServletRequest request, HttpServletResponse response) throws IOException{
			InputStream is = uploadFile.getInputStream();
			XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
			
			Long batchId=new Date().getTime();
			
			 List<Map<String,Object>> skuCodeList = new ArrayList<Map<String,Object>>();
			 List<String> skuList = new ArrayList<>();
			 DecimalFormat df = new DecimalFormat("0");
			
			try {
				// Read the Sheet
				for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
					XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
					if (xssfSheet == null) {
						continue;
					}
					// Read the Row
					for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
						XSSFRow xssfRow = xssfSheet.getRow(rowNum);
						if (xssfRow == null) {
							continue;
						}
						if (xssfRow != null) {
							Map<String,Object> map=new HashMap<String, Object>();
							String contractCode = xssfRow.getCell(2).toString();
							String skuCode = getValue(xssfRow.getCell(3));
							
							String careLableAmount = getValue(xssfRow.getCell(8));
							
							String careLablePrice = xssfRow.getCell(9).toString();
							String barAmount = getValue(xssfRow.getCell(10));
							String barPrice = xssfRow.getCell(11).toString();
							
							String stickerAmount = getValue(xssfRow.getCell(12));
							String stickerType = xssfRow.getCell(13).toString();
							String stickerPrice = xssfRow.getCell(14).toString();
									
							map.put("contractCode", contractCode);
							map.put("skuCode", ""+skuCode);
							map.put("careLableAmount", careLableAmount);
							map.put("careLablePrice", careLablePrice);
							map.put("barAmount", barAmount);
							map.put("barPrice", barPrice);
							map.put("stickerAmount", stickerAmount);
							map.put("stickerType", stickerType);
							map.put("stickerPrice", stickerPrice);								
							map.put("batchId", ""+batchId);	
							map.put("createBy", getSession().getTrueName());
							map.put("createTime", format.format(new Date()));
							String r="";
							
							if(contractCode==null)
								r+="合同编号不能为空";
							if(r!=""){						
								continue;
							}
							if(skuCode==null)
								  r+="SkuCode不能为空";
							/*if(skuList.contains(skuCode)){
								r+="数据重复";
							}else{
								skuList.add(skuCode);
							}	*/
							map.put("remark", r);
							skuCodeList.add(map);

						}
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			return skuCodeList;
		}
		
		@RequestMapping("saveBatchMaterialDetail")	
		@ResponseBody	
		public Message saveBatchSupplierInvoice(String materialDetail,HttpServletRequest request,HttpServletResponse response) {
			List<AdminMaterialDetail> adminMaterial=JSON.parseObject(materialDetail, new TypeReference<List<AdminMaterialDetail>>(){});
			
			adminMaterialDetailService.saveBatchMaterialDetail(adminMaterial);
			return SUCCESS_MESSAGE;		
		}
		
		@RequestMapping("exportMaterialDetail")
		public void exportMaterialDetail(Long bathId,String contractCode,HttpServletRequest request,HttpServletResponse response){
			List<AdminMaterialDetail> list = adminMaterialDetailService.selectMaterialDetail(bathId, contractCode);
			byte[] bytes = fileService.downloadFromOss("template/export_material_detail.xlsx"); 
			List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
			Map<String, Object> dataMap = new HashMap<String, Object>();

			dataMap.put("resultSet", list);
			dataMaps.add(dataMap);
			DocumentHandler.DownloadExcel(bytes, "辅料明细.xlsx", dataMap, request, response);
			
		}
	/*	@RequestMapping("exportMaterialTotal")
		public void exportMaterialTotal(String bathId,String contractCode,HttpServletRequest request,HttpServletResponse response){
			List<AdminMaterialDetail> list = adminMaterialDetailService.selectMaterialTotal(bathId, contractCode);
			byte[] bytes = fileService.downloadFromOss("template/material_detail.xlsx"); 
			List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
			Map<String, Object> dataMap = new HashMap<String, Object>();

			dataMap.put("resultSet", list);
			dataMaps.add(dataMap);
			DocumentHandler.DownloadExcel(bytes, "辅料明细统计.xlsx", dataMap, request, response);
			
		}*/
		
		@SuppressWarnings("static-access")
		private String getValue(XSSFCell hssfCell) {
			if (hssfCell == null)
				return null;
			
			if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
				// 返回布尔类型的值
				return String.valueOf(hssfCell.getBooleanCellValue());
			} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
				DecimalFormat df = new DecimalFormat("0");
				String str = df.format(hssfCell.getNumericCellValue());
				// 返回数值类型的值
				return str;
			} else {
				// 返回字符串类型的值
				return hssfCell.getStringCellValue();
			}
		}



	
}
